<template>
  <div class="order-page">
    <div class="container">
      <h2 style="margin: 16px 0;">我的订单</h2>

      <a-table :data-source="orders" :columns="columns" :loading="loading" row-key="id" :pagination="false">
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="statusColor(text)">{{ text }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'createdAt'">
            {{ formatDate(text) }}
          </template>
        </template>
      </a-table>

      <div style="margin-top: 16px;">
        <a-button @click="goHome">返回首页</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { orderAPI } from '@/api/order'
import { hotelAPI } from '@/api/hotel'
import { roomAPI } from '@/api/room'

const router = useRouter()
const loading = ref(false)
const orders = ref([])

const columns = [
  { title: '订单ID', dataIndex: 'id', width: 100 },
  { title: '酒店名称', dataIndex: 'hotelName', width: 160 },
  { title: '房间名称', dataIndex: 'roomName', width: 160 },
  { title: '状态', dataIndex: 'status', width: 120 },
  { title: '金额', dataIndex: 'amount', width: 120 },
  { title: '下单时间', dataIndex: 'createdAt', width: 180 }
]

const statusColor = (s) => s === 'PAID' ? 'green' : (s === 'CANCELLED' ? 'red' : 'blue')
const formatDate = (dt) => { try { return new Date(dt).toLocaleString('zh-CN') } catch { return '-' } }

const loadOrders = async () => {
  const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
  if (!user?.id) { router.push('/login'); return }
  loading.value = true
  try {
    // 仅拉取当前用户的订单
    const res = await orderAPI.list(user.id)
    const payload = res.data?.data || res.data || []
    const rawOrders = Array.isArray(payload) ? payload : (payload.list || [])

    // 提取所需的 hotelId、roomId 集合
    const hotelIds = Array.from(new Set(rawOrders.map(o => o.hotelId).filter(Boolean)))
    const roomGroupByHotel = new Map()

    // 拉取涉及到的酒店名称
    const hotelIdToName = {}
    await Promise.all(hotelIds.map(async (hid) => {
      try {
        const hres = await hotelAPI.detail(hid)
        const h = hres.data?.data || hres.data || {}
        if (h && h.name) hotelIdToName[hid] = h.name
      } catch (e) {
        console.debug('load hotel name failed:', hid, e)
      }
    }))

    // 按酒店分组房间ID，并仅按需拉取对应酒店下的房间列表进行映射
    rawOrders.forEach(o => {
      if (!o.hotelId || !o.roomId) return
      if (!roomGroupByHotel.has(o.hotelId)) roomGroupByHotel.set(o.hotelId, new Set())
      roomGroupByHotel.get(o.hotelId).add(o.roomId)
    })

    const roomIdToName = {}
    for (const [hid, roomIdSet] of roomGroupByHotel.entries()) {
      try {
        const rres = await roomAPI.list(hid, 1, 500)
        const rpayload = rres.data?.data || rres.data || {}
        const rlist = Array.isArray(rpayload) ? rpayload : (rpayload.list || [])
        rlist.forEach(r => {
          if (roomIdSet.has(r.id)) roomIdToName[r.id] = r.roomType || r.room_type
        })
      } catch (e) {
        console.debug('load rooms failed for hotel:', hid, e)
      }
    }

    // 丰富订单展示字段
    orders.value = rawOrders.map(o => ({
      ...o,
      hotelName: hotelIdToName[o.hotelId] || String(o.hotelId || ''),
      roomName: roomIdToName[o.roomId] || String(o.roomId || '')
    }))
  } catch (e) {
    // 忽略错误
  } finally {
    loading.value = false
  }
}

const goHome = () => router.push('/')

onMounted(() => { loadOrders() })
</script>

<style scoped>
.order-page { padding: 16px 0; }
.container { max-width: 960px; margin: 0 auto; padding: 0 16px; }
</style>


